package com.hk.webapp.utils;

import com.google.common.collect.Lists;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

public class EHCacheUtils {

    private static final String CACHE_NAME = "cnread";

    /**
     * 设置缓存对象
     *
     * @param cacheManager
     * @param key
     * @param object
     * @param timeout
     */
    public static void setCache(CacheManager cacheManager, String key, Object object, int timeout) {
        timeout = timeout < 0 ? 0 : timeout;
        Cache cache = cacheManager.getCache(CACHE_NAME);
        Element element;
        if (timeout == 0) {
            element = new Element(key, object);
        } else {
            element = new Element(key, object, timeout, timeout);
        }
        cache.put(element);
    }

    /**
     * 从缓存中取出对象
     *
     * @param cacheManager
     * @param key
     * @return
     */
    public static Object getCache(CacheManager cacheManager, String key) {
        Object object = null;
        Cache cache = cacheManager.getCache(CACHE_NAME);
        if (cache.isKeyInCache(key) && !Objects.isNull(cache.getQuiet(key))) {
            object = cache.get(key).getObjectValue();
        }
        return object;
    }

    /**
     * 从缓存中取出所有对象
     *
     * @param cacheManager
     * @return
     */
    public static <T> List<T> getAllCache(CacheManager cacheManager) {
        T t;
        List<T> list = Lists.newArrayList();
        Cache cache = cacheManager.getCache(CACHE_NAME);
        List keys = cache.getKeys();
        if (!CollectionUtils.isEmpty(keys)) {
            for (Object key : keys) {
                if (cache.isKeyInCache(key) && !Objects.isNull(cache.getQuiet(key))) {
                    t = (T)cache.get(key).getObjectValue();
                    list.add(t);
                }
            }
        }
        return list;
    }

    /**
     * 从缓存中删除对象
     *
     * @param cacheManager
     * @param key
     * @return
     */
    public static void deleteCache(CacheManager cacheManager, String key) {
        Cache cache = cacheManager.getCache(CACHE_NAME);
        if (cache.isKeyInCache(key) && !Objects.isNull(cache.getQuiet(key))) {
            cache.remove(key);
        }
    }


    /**
     * 删除缓存中所有对象
     *
     * @param cacheManager
     * @return
     */
    public static void deleteAllCache(CacheManager cacheManager) {
        Cache cache = cacheManager.getCache(CACHE_NAME);
        List keys = cache.getKeys();
        if (!CollectionUtils.isEmpty(keys)) {
            for (Object key : keys) {
                if (cache.isKeyInCache(key) && !Objects.isNull(cache.getQuiet(key))) {
                    cache.remove(key);
                }
            }
        }
    }

}
